/*
 * @lc app=leetcode.cn id=143 lang=javascript
 *
 * [143] 重排链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function (head) {
  if (!head) {
    return null
  }

  const middleNode = getMiddle(head)
  let l1 = head, l2 = middleNode.next
  middleNode.next = null
  l2 = reverseList(l2)
  mergeList(l1, l2)

  function getMiddle (head) {
    let slow = head, fast = head

    while (fast.next && fast.next.next) {
      slow = slow.next
      fast = fast.next.next
    }

    return slow
  }
  function reverseList (head) {
    let prevNode = null, currNode = head

    while (currNode) {
      let tempNode = currNode.next
      currNode.next = prevNode
      prevNode = currNode
      currNode = tempNode
    }

    return prevNode
  }
  function mergeList (l1, l2) {
    while (l1 && l2) {
      let tempL1 = l1.next, tempL2 = l2.next
      l1.next = l2
      l1 = tempL1
      l2.next = l1
      l2 = tempL2
    }
  }
};
// @lc code=end

